package com.ruoyi.web.web.controller;

import com.ruoyi.accountant.domain.Reason;
import com.ruoyi.accountant.service.ReasonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/reason")
public class ReasonController {

    @Autowired
    private ReasonService reasonService;

    @PostMapping("/add")
    public String add(Reason reason) {
        reasonService.save(reason);
        reason.setLevel(1);
        return "redirect:/pages/item/reason.html";
    }

    /****
     * 增加子原因
     * @param reason
     * @return
     */
    @PostMapping("/addsub")
    public String addsub(Reason reason) {
        Long rid = reason.getRid();
        reason.setRid(null);

        reason.setLevel(reasonService.findById(reason.getParent()).getLevel() + 1);

        reasonService.save(reason);

        return "redirect:/reason/subreason.html?rid="+rid;
    }

    @PostMapping("/update")
    public String update(Reason form) {
        Reason reason = reasonService.findById(form.getRid());
        reason.setRcode(form.getRcode());
        reason.setRname(form.getRname());
        reasonService.update(reason);

        return "redirect:/pages/item/reason.html";
    }

    @PostMapping("/updatesub")
    public String updatesub(Reason form) {
        Reason reason = reasonService.findById(form.getRid());
        reason.setRcode(form.getRcode());
        reason.setRname(form.getRname());
        reasonService.update(reason);

        return "redirect:/reason/subreason.html?rid="+reason.getParent();
    }

    @GetMapping("/delete")
    public String delete(Long rid) {
        reasonService.deleteById(rid);

        return "redirect:/pages/item/reason.html";
    }

    /***
     * 子分类
     * @param rid
     * @param model
     * @return
     */
    @GetMapping("/subreason.html")
    public String subreason(Long rid, Model model) {
        Reason reason = reasonService.findById(rid);
        List<Reason> reasonList = reasonService.findAllByParent(rid);

        model.addAttribute("parentReason", reason);
        model.addAttribute("reasonList", reasonList);
        return "pages/item/subreason";
    }

    /***
     * 上一级
     * @param rid
     * @return
     */
    @GetMapping("/uplevel")
    public String uplevel(Long rid) {
        Reason reason = reasonService.findById(rid);
        if(reason.getParent() == -1) {
            return "redirect:/pages/item/reason.html";
        } else {
            return "redirect:/reason/subreason.html?rid="+reason.getParent();
        }
    }
}
